package util;

import android.text.TextUtils;

import com.apkfuns.logutils.LogUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StrUtil {

    public static final String EMPTY = "";
    /**
     * <p>
     * The maximum size to which the padding constant(s) can expand.
     * </p>
     */
    private static final int PAD_LIMIT = 8192;


    public static boolean isBlank(CharSequence cs) {
        int strLen;
        if (cs != null && (strLen = cs.length()) != 0) {
            for (int i = 0; i < strLen; ++i) {
                if (!Character.isWhitespace(cs.charAt(i))) {
                    return false;
                }
            }

            return true;
        } else {
            return true;
        }
    }

    public static boolean isNotBlank(CharSequence cs) {
        return !isBlank(cs);
    }

    public static boolean isVaildGoogleRating(String str) {
        if (isBlank(str)) return false;
        double rating = Double.valueOf(str);
        if (rating <= 0) return false;
        return true;
    }

    public static String streamToString(java.io.InputStream is) throws IOException {
        try {
            if (is != null) {
                StringBuilder sb = new StringBuilder();
                String line;
                try {
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(is, "UTF-8"));
                    while ((line = reader.readLine()) != null) {
                        sb.append(line).append("\n");
                    }
                } finally {
                    is.close();
                }
                return sb.toString();
            } else {
                return "";
            }
        } catch (Exception ex) {
            LogUtils.e(ex);
        }
        return "";
    }

//    public static boolean isEmail(String strEmail) {
//        String strPattern = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
//        Pattern p = Pattern.compile(strPattern);
//        Matcher m = p.matcher(strEmail);
//        if (m.matches()) {
//            return true;
//        } else {
//            return false;
//        }
//    }

    public static boolean isEmailByASCII(String strEmail) {
        String strPattern = "[\\x00-\\xff]+@[\\x00-\\xff]+\\.[\\x00-\\xff]+";
        Pattern p = Pattern.compile(strPattern);
        Matcher m = p.matcher(strEmail);
        if (m.matches()) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean isCellphone(String str) {
        String strPattern = "1[3578]\\d{9}";
        Pattern pattern = Pattern.compile(strPattern);
        Matcher matcher = pattern.matcher(str);
        if (matcher.matches()) {
            return true;
        } else {
            return false;
        }
    }

    public static String getCutString(String str, int length) {
        if (str != null && str.length() > length) {
            return str.substring(0, length);
        }
        return str;
    }

    public static String getCutString(String str, int length, String suffix) {
        if (str != null && str.length() > length) {
            return str.substring(0, length - 1) + suffix;
        }
        return str;
    }

    public static boolean isQq(String str) {
        String strPattern = "\\d{5,11}";
        Pattern pattern = Pattern.compile(strPattern);
        Matcher matcher = pattern.matcher(str);
        if (matcher.matches()) {
            return true;
        } else {
            return false;
        }
    }

    public static String getEmialWebHostWebLoginAddress(String email) {
        if (email.contains("@")) {
            String url = email.substring(email.indexOf("@") + 1);
            url = "http://mail." + url;
            return url;
        }
        return null;
    }

    public static String getEmialWebHostWebLoginAddress(String email, String hostPre) {
        if (email.contains("@")) {
            String url = email.substring(email.indexOf("@") + 1);
            url = TextUtils.isEmpty(hostPre) ? "http://mail." : hostPre + url;
            return url;
        }
        return null;
    }

    public static double getDouble(String str) {
        double result = 0;
        try {
            result = Double.valueOf(str);
        } catch (Exception e) {
            // TODO: handle exception
        }
        return result;
    }

    public static String parseTo_HH_mm_ss(int second) {

        int day = (int) (second / 60 / 60 / 24);
        int hh = (int) ((second - (day * 24 * 60 * 60)) / 60 / 60);
        int mm = (int) ((second - (day * 24 * 60 * 60) - (hh * 60 * 60)) / 60);
        int ss = (int) (second - (day * 24 * 60 * 60) - (hh * 60 * 60) - (mm * 60));

        StringBuilder sb = new StringBuilder();
        if (day > 0)
            sb.append(day + "#");
        if (hh > 0)
            sb.append(hh + "##");
        if (mm > 0)
            sb.append(mm + "##");
        sb.append(ss + "#");
        return sb.toString();
    }

    public static String parseTo_HH_mm(int second) {

        int day = (int) (second / 60 / 60 / 24);
        int hh = (int) ((second - (day * 24 * 60 * 60)) / 60 / 60);
        int mm = (int) ((second - (day * 24 * 60 * 60) - (hh * 60 * 60)) / 60);
        int ss = (int) (second - (day * 24 * 60 * 60) - (hh * 60 * 60) - (mm * 60));

        StringBuilder sb = new StringBuilder();
        if (day > 0)
            sb.append(day + "#");
        if (hh > 0)
            sb.append(hh + "##");
        if (mm > 0)
            sb.append(mm + "##");
        return sb.toString();
    }

    public static String parseDotNetDateToSimpleDateFriendlyString(String str) {
        // Date(1416135171847+0800)
        str = str.substring(6, 19);
        long miss = Long.parseLong(str);
        Date start = new Date(miss);
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");

        Date end = new Date();
        String result = "";
        long between = (end.getTime() - start.getTime()) / 1000;// ##1000#######
        long day1 = between / (24 * 3600);
        long hour1 = between % (24 * 3600) / 3600;
        long minute1 = between % 3600 / 60;
        long second1 = between % 60 / 60;
        if (day1 > 0) {
            result = day1 + "##";
            if (day1 >= 15) {
                result = "###";
                if (day1 >= 30) {
                    result = "####";
                    if (day1 >= 60) {
                        result = "2###";
                        if (day1 >= 90) {
                            result = "3###";
                            if (day1 >= 180) {
                                result = "###";
                                if (day1 >= 365) {
                                    result = "###";
                                    if (day1 >= 730) {
                                        result = sf.format(start);
                                    }
                                }

                            }
                        }
                    }
                }
            }
            return result;
        }
        if (hour1 > 0) {
            result = hour1 + "###";
            return result;
        }
        if (minute1 > 0) {
            result = minute1 + "###";
            return result;
        }

        result = "##";
        return result;

    }

    public static String ValidFileName(String str) {
        if (str == null) {
            return str;
        }
        return str.replace("\\", "-1-").replace("/", "-2-").replace(":", "-3-").replace("*", "-4-").replace("?", "-5-")
                .replace("\"", "-6-").replace("<", "-7-").replace(">", "-8-").replace("|", "-9-");
    }

    public static String urlEncode(String str) {
        try {
            return URLEncoder.encode(str, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    public static String[] stringToArrayByNewline(String method) {

        String[] strs = method.split("\r\n");
        return strs;
    }

    public static String getFileNameWithoutExt(String fileName) {
        return fileName.substring(0, fileName.lastIndexOf("."));
    }

    public static String rightPad(String str, int size) {
        return rightPad(str, size, ' ');
    }

    public static String rightPad(String str, int size, char padChar) {
        if (str == null) {
            return null;
        }
        int pads = size - str.length();
        if (pads <= 0) {
            return str; // returns original String when possible
        }
        if (pads > PAD_LIMIT) {
            return rightPad(str, size, String.valueOf(padChar));
        }
        return str.concat(padding(pads, padChar));
    }

    public static String rightPad(String str, int size, String padStr) {
        if (str == null) {
            return null;
        }
        if (padStr == null || padStr.isEmpty()) {
            padStr = " ";
        }
        int padLen = padStr.length();
        int strLen = str.length();
        int pads = size - strLen;
        if (pads <= 0) {
            return str; // returns original String when possible
        }
        if (padLen == 1 && pads <= PAD_LIMIT) {
            return rightPad(str, size, padStr.charAt(0));
        }

        if (pads == padLen) {
            return str.concat(padStr);
        } else if (pads < padLen) {
            return str.concat(padStr.substring(0, pads));
        } else {
            char[] padding = new char[pads];
            char[] padChars = padStr.toCharArray();
            for (int i = 0; i < pads; i++) {
                padding[i] = padChars[i % padLen];
            }
            return str.concat(new String(padding));
        }
    }

    private static String padding(int repeat, char padChar) throws IndexOutOfBoundsException {
        if (repeat < 0) {
            throw new IndexOutOfBoundsException("Cannot pad a negative amount: " + repeat);
        }
        final char[] buf = new char[repeat];
        for (int i = 0; i < buf.length; i++) {
            buf[i] = padChar;
        }
        return new String(buf);
    }

    public static String substring(String str, int start) {
        if (str == null) {
            return null;
        }

        // handle negatives, which means last n characters
        if (start < 0) {
            start = str.length() + start; // remember start is negative
        }

        if (start < 0) {
            start = 0;
        }
        if (start > str.length()) {
            return "";
        }

        return str.substring(start);
    }

    public static String substring(String str, int start, int end) {
        if (str == null) {
            return null;
        }

        // handle negatives
        if (end < 0) {
            end = str.length() + end; // remember end is negative
        }
        if (start < 0) {
            start = str.length() + start; // remember start is negative
        }

        // check length next
        if (end > str.length()) {
            end = str.length();
        }

        // if start is greater than end, return ""
        if (start > end) {
            return "";
        }

        if (start < 0) {
            start = 0;
        }
        if (end < 0) {
            end = 0;
        }

        return str.substring(start, end);
    }

    public static String fixUrl(String url) {
        if (isBlank(url)) return url;
        //[//media.entertainment.com/media/entertainment/about/images/header_03.gif]
        if (url.startsWith("/")) {
            while (url.startsWith("/")) {
                url = url.substring(1);
            }
            url = "http://" + url;
        }
        return url;
    }

    public static String arrayToString(List<String> array) {
        if (array == null) return "";
        if (array.size() == 0) return "";
        String allString = "";
        for (int i = 0; i < array.size(); i++) {
            allString += array.get(i);
            if (i != array.size() - 1) {
                allString += ",";
            }
        }
        return allString;
    }

    public static String createLinkString(Map<String, String> params) {
        try {
            List<String> keys = new ArrayList<>(params.keySet());
            Collections.sort(keys);
            String prestr = "";
            for (int i = 0; i < keys.size(); i++) {
                String key = keys.get(i);
                String value = params.get(key);
                value = URLEncoder.encode(value, "UTF-8");
                if (i == keys.size() - 1) {//###，#######&##
                    prestr = prestr + key + "=" + value;
                } else {
                    prestr = prestr + key + "=" + value + "&";
                }
            }
            return prestr;
        } catch (Exception ex) {
            LogUtils.e(ex);
        }
        return "";
    }

    public static String contactString(List<String> list) {
        String memberNames = "";
        for (int t = 0; t < list.size(); t++) {
            String memTemp = list.get(t);
            if (memTemp != null) {
                memberNames += memTemp + ",";
            }
        }
        if (memberNames.length() > 0)
            memberNames = memberNames.substring(0, memberNames.length() - 1);
        return memberNames;
    }

    public static String contactStringWith(String split, String... paras) {
        StringBuilder memberNames = new StringBuilder();
        for (int t = 0; t < paras.length; t++) {
            String memTemp = paras[t];
            if (isNotBlank(memTemp)) {
                memberNames.append(memTemp);
                memberNames.append(split);
            }
        }
        return memberNames.toString().trim();
    }

    public static String getLocationId(String merchantId) {
        //"merchantId": "MCM50215092_1744410_RV7", ###### merchant id， #### location id
        if (isBlank(merchantId)) return "";
        String[] parts = merchantId.split("_");
        if (parts.length < 3) return "";
        return parts[1];
    }

    public static boolean isInArray(int id, int[] ids) {
        for (int i : ids) {
            if (id == i) {
                return true;
            }
        }
        return false;
    }
}